<template>
  <q-page>
    <template
      v-for="(acc, index) in $store.getters['persisted/accounts']"
      :key="index"
    >
      <div
        class="row column min-height-inherit"
        v-if="webviews[acc.userid]"
        v-show="acc.userid === $route.query.id"
      >
        <div class="col-auto nav-tag bg-grey-3 row">
          <div class="tool col-auto flex items-center on-left q-gutter-x-sm">
            <q-btn
              :color="data.canGoBack ? 'dark' : 'grey'"
              size="sm"
              icon="iconfont icon-arrow-left-bold"
              dense
              flat
              round
              :disable="!data.canGoBack"
              @click="back"
            />
            <q-btn
              :color="data.canGoForward ? 'dark' : 'grey'"
              size="sm"
              icon="iconfont icon-arrow-right-bold"
              dense
              flat
              round
              :disable="!data.canGoForward"
              @click="forward"
            />
            <q-btn
              color="dark"
              size="sm"
              icon="iconfont icon-close-bold"
              dense
              flat
              round
              v-if="data.loading"
              @click="stop"
            />
            <q-btn
              color="dark"
              size="sm"
              icon="iconfont icon-shuaxin"
              dense
              flat
              round
              v-else
              @click="refresh"
            />
          </div>
          <div class="col nav-bar row no-wrap">
            <template v-for="(view, vi) in webviews[acc.userid].list" :key="vi">
              <div
                class="nav-control col flex items-center no-wrap non-selectable"
                :class="{ active: webviews[acc.userid].currentIndex === vi }"
                @click="webviews[acc.userid].currentIndex = vi"
              >
                <q-spinner color="grey" v-if="view.loading" class="on-left" />
                <q-icon
                  :name="`img:${view.favicon}`"
                  v-if="view.favicon && !view.loading"
                  class="on-left"
                />
                <div class="ellipsis text-caption">
                  {{ view.title }}
                </div>
                <q-btn
                  icon="close"
                  flat
                  size="xs"
                  dense
                  v-if="webviews[acc.userid].list.length > 1"
                  @click.stop="view.close"
                />
              </div>
            </template>
          </div>
        </div>
        <div class="col relative-position">
          <template v-for="(view, vi) in webviews[acc.userid].list" :key="vi">
            <webview
              :ref="view.ref"
              class="full-width full-height absolute-top-left"
              style="vertical-align: top"
              v-bind="view.bind"
              v-show="webviews[acc.userid].currentIndex === vi"
            >
            </webview>
          </template>
        </div>
      </div>
    </template>
  </q-page>
</template>

<style lang="scss" scoped>
.nav-tag {
  padding: 0 8px;
  .nav-bar {
    position: relative;
    overflow-y: clip;
  }
  .nav-control {
    cursor: default;
    &::before {
      content: "";
      width: 1px;
      background: #ccc;
      /* height: 100%; */
      left: 0;
      position: absolute;
      /* line-height: 100%; */
      top: 9px;
      bottom: 9px;
    }
    &.active {
      background-color: white;
      box-shadow: 0 1px 5px rgb(0 0 0 / 20%), 0 2px 2px rgb(0 0 0 / 14%),
        0 3px 1px -2px rgb(0 0 0 / 12%);
      &::before {
        content: "";
        position: absolute;
        top: auto;
        bottom: 0;
        width: 8px;
        height: 8px;
        left: -8px;
        background: radial-gradient(circle at 0% 0%, transparent 8px, white 0);
      }
      &::after {
        content: "";
        position: absolute;
        top: auto;
        bottom: 0;
        width: 8px;
        height: 8px;
        right: -8px;
        background: radial-gradient(
          circle at 100% 0%,
          transparent 8px,
          white 0
        );
      }
    }
    max-width: 240px;
    position: relative;
    margin-top: 6px;
    padding: 10px 12px;
    border-top-left-radius: 8px;
    border-top-right-radius: 8px;
  }
}
</style>

<script>
import {
  computed,
  defineComponent,
  inject,
  nextTick,
  onMounted,
  onUnmounted,
  reactive,
  ref,
  watch,
} from "vue";
import { useRoute } from "vue-router";

export default defineComponent({
  name: "PagesBrowserPageVue",
  setup() {
    const $route = useRoute();
    const webviews = ref({});
    let viewIndex = 0;
    function openURL(userid, url) {
      viewIndex++;
      if (!webviews.value[userid]) {
        webviews.value[userid] = {
          currentIndex: 0,
          list: [],
        };
      }
      const xhr = reactive({
        id: viewIndex,
        $el: null,
        ref(el) {
          xhr.$el = el;
        },
        _url: "",
        loading: false,
        title: "新标签页",
        favicon: null,
        isReady: false,
        bind: {
          src: url,
          partition: `persist:zbj_${userid}`,
          nodeintegration: true,
          allowpopups: true,
          preload: window.electron.utils.preload,
        },
        close() {
          const index = webviews.value[userid].list.indexOf(xhr);
          if (index <= webviews.value[userid].currentIndex) {
            webviews.value[userid].currentIndex--;
          }
          webviews.value[userid].list.splice(index, 1);
        },
      });
      const len = webviews.value[userid].list.push(xhr);
      webviews.value[userid].currentIndex = len - 1;
      nextTick(() => {
        if (!xhr.$el) {
          console.log("webview 未加载");
          return;
        }
        xhr.$el.addEventListener("dom-ready", () => {
          xhr.isReady = true;
        });
        xhr.$el.addEventListener("did-start-loading", () => {
          xhr.loading = true;
          data.loading = true;
        });
        xhr.$el.addEventListener("did-stop-loading", (e) => {
          xhr.loading = false;
          data.loading = false;
          xhr._url = xhr.$el.getURL();
        });
        xhr.$el.addEventListener("page-title-updated", (e) => {
          xhr.title = e.title;
        });
        xhr.$el.addEventListener("page-favicon-updated", (e) => {
          xhr.favicon = e.favicons[0];
        });
        xhr.$el.addEventListener("ipc-message", (e) => {
          switch (e.channel) {
            case "new-window":
              const details = e.args[0];
              openURL(userid, details.url);
              break;
          }
        });
      });
    }

    const data = reactive({
      loading: false,
      canGoBack: computed(() => {
        const xhr = getCurrentView();
        if (!xhr || !xhr.$el || !xhr.isReady || !xhr._url) {
          return false;
        }
        return xhr.$el.canGoBack();
      }),
      canGoForward: computed(() => {
        const xhr = getCurrentView();
        if (!xhr || !xhr.$el || !xhr.isReady || !xhr._url) {
          return false;
        }
        return xhr.$el.canGoForward();
      }),
      defaultURL: "https://jdyboss.zbj.com/?supei=1",
    });

    watch(
      () => [$route.query.id, $route.query.url],
      ([userid, url]) => {
        if (userid) {
          const list = webviews.value[userid];
          if (list) {
            return;
          }
          openURL(userid, url || data.defaultURL);
        }
      },
      {
        immediate: true,
      }
    );

    function getCurrentView() {
      if (!webviews.value) {
        return;
      }
      const collection = webviews.value[$route.query.id];
      if (collection) {
        return collection.list[collection.currentIndex];
      }
    }

    function back() {
      const xhr = getCurrentView();
      if (xhr.isReady && xhr.$el.canGoBack()) {
        xhr.$el.goBack();
      }
    }
    function forward() {
      const xhr = getCurrentView();
      if (xhr.isReady && xhr.$el.canGoForward()) {
        xhr.$el.goForward();
      }
    }
    function refresh() {
      const xhr = getCurrentView();
      if (xhr.isReady) {
        xhr.$el.reload();
      }
    }
    function stop() {
      const xhr = getCurrentView();
      if (xhr.isReady) {
        xhr.$el.stop();
      }
    }

    return { data, webviews, back, forward, refresh, stop };
  },
});
</script>
